import { SearchOutlined, UsergroupAddOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Input, message } from 'antd';
import React, { useState } from 'react';
import http from '~/api/http';
import type { IGanyut } from '~/types/ganyut';
import type { IGanyuxadd } from '~/types/ganyux';

const quizQuestions = [
  {
    id: 1,
    question: "头痛或者感觉身体疼",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id: 2,
    question: "担心自己的服饰整齐及仪态端正,以及想把不整齐或者不合理的事务弄正",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id: 3,
    question: "同事聚餐时没人主动和自己搭话，会认为 “他们不喜欢我”，而非 “大家在聊各自熟悉的话题",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id: 4,
    question: "在选择或行动前反复纠结、难以定夺，甚至因过度权衡而延迟或放弃决策",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id: 5,
    question: "社交焦虑者：想到要参加聚会、当众发言，会提前几小时开始心跳加速、手心出汗，甚至找借口拒绝",
    options: [
     { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id: 6,
    question: "朋友提出不同意见时，不反驳但会立刻沉默，拒绝继续沟通",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id:7,
    question: "夜晚独自走夜路时，突然听到身后有快速脚步声，会瞬间感到 “心脏骤停” 般的恐惧，脑海里立刻闪过 “被袭击” 的画面",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id:8,
    question: "同事开会时低头记录，会认为 “他在偷偷记我的缺点，准备打小报告",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  },
  {
    id:9,
    question: "听到多人在讨论自己（“评论性幻听”：“他是个坏人”“他做的事真恶心”）",
    options: [
      { text: "从无", score: 0},
      { text: "轻度", score: 1 },
      { text: "中度", score: 2 },
      { text: "偏重", score: 3},
      { text: "严重", score: 4 }
    ]
  }
];

const questionColumnMap = [
  { questionId: 1, columnName: "q1_score" }, // 第1题分数 → 列q1_score
  { questionId: 2, columnName: "q2_score" }, // 第2题分数 → 列q2_score
  { questionId: 3, columnName: "q3_score" }, // 第3题分数 → 列q3_score
  { questionId: 4, columnName: "q4_score" }, // 第4题分数 → 列q4_score
  { questionId: 5, columnName: "q5_score" }, // 第5题分数 → 列q5_score
  { questionId: 6, columnName: "q6_score" }, // 第6题分数 → 列q6_score
  { questionId: 7, columnName: "q7_score" }, // 第7题分数 → 列q7_score
  { questionId: 8, columnName: "q8_score" }, // 第8题分数 → 列q8_score
  { questionId: 9, columnName: "q9_score" }, // 第9题分数 → 列q9_score
];
interface AddFormProps {
  onSuccess?: () => void; // 提交成功的回调
  onCancel?: () => void;  // 关闭弹窗的回调
}
const calculateTotalPossibleScore = () => {
  return quizQuestions.reduce((total, question) => {
    const maxScore = Math.max(...question.options.map(option => option.score));
    return total + maxScore;
  }, 0);
};

const FinalScoreQuiz:React.FC<AddFormProps> = ({onSuccess,onCancel}) => {
  // 存储每道题的选择（包含选项文本和分数）
  const [questionScores, setQuestionScores] = useState(
    quizQuestions.map(question => ({
      questionId: question.id,
      questionText: question.question,
      selectedText: null, // 所选选项文本
      selectedScore: null, // 所选选项分数
      isAnswered: false // 是否已回答
    }))
  );

  const [submitted, setSubmitted] = useState(false);
  const [totalScore, setTotalScore] = useState(0);
  const totalPossibleScore = calculateTotalPossibleScore();
  const [isVisible, setIsVisible] = React.useState(true);

  // 处理选项选择：实时更新当前题目的分数
  const handleOptionSelect = (questionIndex, option) => {
    if (submitted) return;

    const updatedScores = [...questionScores];
    // 更新当前题目的选择结果
    updatedScores[questionIndex] = {
      ...updatedScores[questionIndex],
      selectedText: option.text,
      selectedScore: option.score,
      isAnswered: true
    };
    setQuestionScores(updatedScores);
  };

  const ganyux1:IGanyuxadd={
    id: 0,
    xdata:new Date,
    xin: 0,
    xin1: 0,
    xin2: 0,
    xin3: 0,
    xin4: 0,
    xin5: 0,
    xin6: 0,
    xin7: 0,
    xin8: 0,
    bid: 0
  }
  // 提交时计算总分，并标记提交状态
  const handleSubmit = () => {
    const allAnswered = questionScores.every(item => item.isAnswered);
    if (!allAnswered) {
      alert("请完成所有题目后再提交");
      return;
    }

    // 计算总分（累加每道题的所选分数）
    const sum = questionScores.reduce((total, item) => total + item.selectedScore, 0);
    setTotalScore(sum);
    setSubmitted(true);
   
console.log(ganyux1)
  };

  // 重新开始：重置所有选择和分数
  const handleRestart = () => {
    setQuestionScores(
      quizQuestions.map(question => ({
        questionId: question.id,
        questionText: question.question,
        selectedText: null,
        selectedScore: null,
        isAnswered: false
      }))
    );
    setSubmitted(false);
    setTotalScore(0);
  };
    const [inputvalue,setinputvalue]=useState('')
      const [name,setname]=useState('')
      const [sex,setsex]=useState('')
      const [age,setage]=useState(0)
      const [bid,setbid]=useState(0)
const changeCount1 = (event: React.ChangeEvent<HTMLInputElement>) => {
        setinputvalue(event.target.value);
}
const fetchUsers = async (value:string) => {
    
    const response = await http.getList<IGanyut>('Order/chay', {})
 
 const bb=response.data.filter(u=>u.fileNumber==value&&u.orderStatus=='正在体检')
 
  if (bb.length>0) {  
  setname(bb[0].name)
  setage(bb[0].age)
   setsex(bb[0].sex)
   setbid(bb[0].hid)
 }else{
 message.warning('未找到匹配的档案信息');
 }
 console.log("ganyux1.bid 赋值后：", ganyux1.bid,"zz",bid); 
  }
  const dian=()=>{
if (inputvalue.trim()) {
      fetchUsers(inputvalue);
    } else {
      message.warning('请输入档案号');
    }
  }
  const jia = async () => {
    
  console.log('11', questionScores[0].selectedScore);
  // 给 ganyux1 赋值（你的原有逻辑不变）
  ganyux1.xin = questionScores[0].selectedScore || 0;
  ganyux1.xin1 = questionScores[1].selectedScore || 0;
  ganyux1.xin2 = questionScores[2].selectedScore || 0;
  ganyux1.xin3 = questionScores[3].selectedScore || 0;
  ganyux1.xin4 = questionScores[4].selectedScore || 0;
  ganyux1.xin5 = questionScores[5].selectedScore || 0;
  ganyux1.xin6 = questionScores[6].selectedScore || 0;
  ganyux1.xin7 = questionScores[7].selectedScore || 0;
  ganyux1.xin8 = questionScores[8].selectedScore || 0;
  ganyux1.bid = bid;
  console.log("hh", ganyux1);

  try {
    const bb = await http.post<IGanyuxadd>('Ganyux', ganyux1);
    // 请求成功后的逻辑（关键：调用 onSuccess 回调）
    
    if (onSuccess) { // 先判断 onSuccess 是否存在，避免报错
     
      onSuccess(); // 执行父组件传来的成功回调（关闭弹窗+刷新页面）
    }
  } catch (error) {
    console.error('请求失败', error);
  }
};
  // 检查是否所有题目都已回答
  const allAnswered = questionScores.every(item => item.isAnswered);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-6 px-4">
        <span style={{ position: 'relative', left: '20px' }}>档案号</span>
          <Input onChange={changeCount1} value={inputvalue}  size="small" style= {{ position: 'relative', left: '30px' ,width:'150px'}} placeholder="档案号..." prefix={<UserOutlined />} /> 
 <Button icon={<SearchOutlined />} style={{position: 'relative', left: '31px', height:25}}  target="_blank" onClick={dian} />
 <span style={{ position: 'relative', left: '40px' }}>姓名:{name}</span>
 <span style={{ position: 'relative', left: '90px' }}>性别:{sex}</span>
 <span style={{ position: 'relative', left: '120px' }}>年龄:{age}</span>
       <Button
         type="primary"
          size="small"
         onClick={jia}
           icon={<UsergroupAddOutlined />}
        style={{left:470, position: 'relative'}}>添加</Button>
      <div style={{ display: isVisible ? 'block' : 'none'}} className="max-w-5xl mx-auto bg-white rounded-xl shadow-lg p-5 md:p-6">
        <h1 className="text-2xl font-bold text-center mb-5 text-indigo-600">心理测试</h1>
        
        {/* 题目列表（带实时分数显示） */}
        <div className="space-y-4">
          {questionScores.map((item, questionIndex) => {
            const currentQuestion = quizQuestions[questionIndex];
            return (
              <div 
                key={item.questionId} 
                className="p-3 rounded-lg transition-all hover:shadow-sm border border-gray-100"
              >
                <div className="flex items-start justify-between mb-2">
                  {/* 题目序号和文本 */}
                  <div className="flex items-start">
                    <span className="flex-shrink-0 w-5 h-5 rounded-full bg-indigo-100 text-indigo-800 flex items-center justify-center font-medium mr-2 mt-0.5 text-sm">
                      {item.questionId}
                    </span>
                    <h3 className="text-base font-semibold text-gray-800">{item.questionText}</h3>
                  </div>
                  
                  {/* 实时显示当前题目的所选分数（未选择时显示“未选择”） */}
                  <div className={`text-sm font-medium ${
                    item.isAnswered ? 'text-green-600' : 'text-gray-400'
                  }`}>
                    {item.isAnswered 
                      ? `已选：${item.selectedText}` 
                      : '未选择'}
                  </div>
                </div>
                
                {/* 选项组 */}
                <div className="pl-7 flex flex-wrap gap-2">
                  {currentQuestion.options.map((option, optionIndex) => {
                    const isSelected = item.selectedScore === option.score && item.selectedText === option.text;
                    
                    // 选项样式（选中状态高亮）
                    let labelClasses = "flex items-center p-1.5 rounded transition-all cursor-pointer whitespace-nowrap text-sm";
                    let radioClasses = "w-3.5 h-3.5 text-indigo-600 focus:ring-indigo-500 border-gray-300";
                    
                    if (!submitted) {
                      labelClasses += isSelected 
                        ? " bg-indigo-50 border border-indigo-200" 
                        : " hover:bg-gray-50";
                    } else {
                      labelClasses += isSelected 
                        ? " bg-indigo-50 border border-indigo-200" 
                        : " bg-gray-50 text-gray-400";
                      radioClasses += " cursor-not-allowed";
                    }
                    
                    return (
                      <label 
                        key={optionIndex}
                        htmlFor={`q${item.questionId}-opt${optionIndex}`}
                        className={labelClasses}
                        onClick={() => handleOptionSelect(questionIndex, option)}
                        style={{ cursor: submitted ? 'default' : 'pointer' }}
                      >
                        <input
                          id={`q${item.questionId}-opt${optionIndex}`}
                          type="radio"
                          name={`question-${item.questionId}`}
                          checked={isSelected}
                          disabled={submitted}
                          className={radioClasses}
                          readOnly
                        />
                        <span className="ml-1.5">
                          {option.text}
                          <span className="ml-1 px-1.2 py-0.2 text-xs bg-gray-100 rounded-full text-gray-700">
                           
                          </span>
                        </span>
                      </label>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
        
        {/* 提交按钮 / 结果展示区 */}
        <div className="mt-5">
          {!submitted ? (
            // 未提交：显示提交按钮
            <button
              onClick={handleSubmit}
              disabled={!allAnswered}
              className={`w-full py-2.5 rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 ${
                allAnswered
                  ? 'bg-indigo-600 text-white hover:bg-indigo-700 focus:ring-indigo-500'
                  : 'bg-gray-200 text-gray-500 cursor-not-allowed'
              }`}
            >
              提交答案（共{questionScores.length}题，已答{questionScores.filter(item => item.isAnswered).length}题）
            </button>
          ) : (
            // 已提交：显示总分 + 每道题分数明细
            <div className="space-y-4">
              {/* 总分展示 */}
              <div className="p-4 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg border border-indigo-100">
                <h3 className="text-xl font-bold text-center mb-2 text-indigo-700">测验完成！</h3>
                {/* <p className="text-center text-lg">
                  你的最终得分：
                  <span className="font-bold text-2xl text-green-600 mx-2">{totalScore}</span>
                  /
                  <span className="text-gray-600 mx-1">{totalPossibleScore}</span>
                </p> */}
                <p className="text-center text-sm text-gray-500 mt-1">
                 心理：{totalScore<18?(totalScore<10?"正常":"中度"):(totalScore>27?"严重":"偏重")}
                </p>
              </div>
              
              {/* 每道题分数明细（折叠面板样式） */}
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <div className="bg-gray-50 px-4 py-2 font-medium text-gray-700">
                  每道心里题明细
                </div>
                <div className="p-3 space-y-2 max-h-60 overflow-y-auto">
                  {questionScores.map(item => (
                    <div key={item.questionId} className="flex justify-between items-center py-1 border-b border-gray-50 last:border-0">
                      <div className="text-sm text-gray-800">
                        第{item.questionId}题：{item.questionText}
                      </div>
                      <div className="text-sm font-medium text-green-600">
                        {item.selectedText}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              
              {/* 重新开始按钮 */}
              <button
                onClick={handleRestart}
                className="w-full py-2.5 bg-indigo-600 text-white rounded-lg font-medium hover:bg-indigo-700 transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
              >
                重新开始测验
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default FinalScoreQuiz;